package com.Lyoto.util.weixin.utils;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.Lyoto.util.weixin.bean.Response.TplResponse;
import com.Lyoto.util.weixin.bean.ValueAndColor;
import com.Lyoto.util.weixin.config.ApiConfig;
import com.Lyoto.util.weixin.bean.template.TplMessageTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-09-20 14:10
 * @Version
 **/
@Slf4j
public class WxClient {
    private String accessToken;
    private int expiresIn;
    private long sendTimes;
    
    public String getAccessToken() throws IOException {
        String grantType = "client_credential";
        StringBuilder param = new StringBuilder();
        param.append("?").append("grant_type=").append(grantType)
             .append("&").append("appid=").append(ApiConfig.appId)
             .append("&").append("secret=").append(ApiConfig.secret);
        String body = HttpUtil.createGet(ApiConfig.URL.accessTokenApi + param).execute().body();
        Map parse = (Map) JSON.parse(body);
        this.expiresIn = (Integer) parse.get("expires_in");
        this.sendTimes = System.currentTimeMillis()/1000;
        return this.accessToken = (String) parse.get("access_token");
    }
    public String sendTplMessage(String url, String userId,String templateId,LinkedHashMap<String, ValueAndColor> kvc){
        if (isExpires()){
            try {
                getAccessToken();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        String authorUrl = new StringBuilder(url).append("?").append("access_token").append("=").append(this.accessToken).toString();
        TplMessageTemplate<JSONObject> template = createTplBody(userId, templateId);
        JSONObject data = template.getData();
        data.putAll(kvc);
        log.info("待发送报文->{}",JSON.toJSONString(template));
        HttpResponse execute = HttpUtil.createPost(authorUrl).body(JSON.toJSONString(template)).execute();
        TplResponse response = JSONObject.parseObject(execute.body(), TplResponse.class);
        log.info("返回结果->{}",execute.body());
        if (response.getErrCode() != 0){
            throw new RuntimeException("信息发送失败");
        }
        return "推送成功";
    }
    
    private TplMessageTemplate<JSONObject> createTplBody(String userId,String templateId){
        TplMessageTemplate<JSONObject> template = new TplMessageTemplate<>();
        template.setToUser(userId);
        template.setTemplateId(templateId);
        template.setData(new JSONObject());
        return template;
    }
    
    /**
     *
     * @return ture 过期 false没有
     * */
    public boolean isExpires(){
        if (accessToken == null){
            try {
                this.getAccessToken();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return (System.currentTimeMillis() / 1000) > (this.sendTimes + this.expiresIn);
    }
    
    public static void main(String[] args) throws IOException {
        System.out.println(new WxClient().getAccessToken());
    }
    
}
